<?php

namespace App\Admin\Extensions\Tools;

use Encore\Admin\Facades\Admin;

class Recommend
{
    private $id, $recommended, $title, $confirm, $cancel, $model;

    public function __construct($id, $recommended, $model)
    {
        $this->id = $id;

        $this->recommended = $recommended;

        $this->model = $model;

        $this->title = trans('admin.recommend');

        $this->confirm = trans('admin.confirm');

        $this->cancel = trans('admin.cancel');
    }

    public function script()
    {
        $route = route('admin.set.recommend');

        return <<<EOT

        $('.recommend-button').on('click',function(){
            var obj = this;
            var id = $(this).attr('data-id');          
            var model = $(this).attr('data-model');          

            swal({
                title: "$this->title",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "$this->confirm",
                allowOutsideClick: false,
                cancelButtonText: "$this->cancel",
            }).then(function(result){
                if(result.value){ 
                    $.ajax({
                        method: 'post',
                        url:   '$route',
                        data: {
                            id:id,
                            model:model,
                            _token:LA.token,
                        },
                        success: function (data) {
                            $.pjax.reload('#pjax-container');
            
                            if (typeof data === 'object') {
                                if (data.status) {
                                    swal(data.message, '', 'success');
                                } else {
                                    swal(data.message, '', 'error');
                                }
                            }
                        }
                    });
                }
            });   
        });
        
EOT;

    }

    protected function render()
    {
        Admin::script($this->script());

        if ($this->recommended) {
            $icon = "<i class='fa fa-star' style='color:red'></i>";
        } else {
            $icon = "<i class='fa fa-star-o'></i>";
        }

        return "<a href='javascript:;' class='recommend-button' data-id='{$this->id}' data-model='{$this->model}' style='margin:2px' title='{$this->title}'>" . $icon . "</a>";
    }

    public function __toString()
    {
        return $this->render();
    }

}
